package leetcode.editor.cn.util.list.singly;

public class ListNode {
    public int val;
    public ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null || head.next.next == null) return false;
        // 快指针
        ListNode quickNode = head.next.next;
        // 慢指针
        ListNode slowNode = head;
        while (quickNode != null) {
            if (quickNode == slowNode) {
                return true;
            }
            quickNode = quickNode.next;
            if (quickNode == null) return false;
            quickNode = quickNode.next;
            slowNode = slowNode.next;
        }
        return false;
    }

    @Override
    public String toString() {
        if (hasCycle(this)) return "链表中存在环！！！！";
        StringBuilder sb = new StringBuilder();

        ListNode cur = this;
        while (cur != null) {
            sb.append(cur.val).append(" -> ");
            cur = cur.next;
        }

        return sb.toString();
    }
}
